package com.bw.module_mine

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bw.lib_storage.db.DBUtils
import com.bw.lib_storage.db.entity.History
import com.bw.module_mine.databinding.ActivityHistoryListBinding
import com.bw.module_mine.model.Adpter.HistoryDetailAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HistoryListActivity : AppCompatActivity() {
    private lateinit var binding: ActivityHistoryListBinding
    private lateinit var historyAdapter: HistoryDetailAdapter
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHistoryListBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 设置标题
        binding.tvTitle.text = "观看历史"
        
        // 设置返回按钮
        binding.ivBack.setOnClickListener {
            finish()
        }
        
        // 初始化RecyclerView
        binding.rvHistory.layoutManager = LinearLayoutManager(this)
        
        // 加载历史记录
        loadAllHistory()
    }
    
    // 加载所有历史记录
    private fun loadAllHistory() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val historyList = DBUtils.getDB().historyDao().getAllHistory()
                    .toMutableList()
                    .apply { reverse() } // 最新的在前面
                
                withContext(Dispatchers.Main) {
                    historyAdapter = HistoryDetailAdapter(this@HistoryListActivity, historyList)
                    binding.rvHistory.adapter = historyAdapter
                    
                    // 设置点击事件
                    historyAdapter.setOnItemClickListener(object : HistoryDetailAdapter.OnItemClickListener {
                        override fun onItemClick(history: History) {
                            // 跳转到视频播放页面

                        }
                    })
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}